package ua.kpi.ipsa.expert.api.client;

import java.awt.*;
import java.awt.event.*;
import java.rmi.*;
import java.text.*;
import java.util.*;
import java.util.List;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;

import net.miginfocom.swing.*;
import ua.kpi.ipsa.expert.api.net.*;

/**
 * 
 * @author doctorpro
 * 
 */
public class CodePortionBrowser extends JPanel implements ActionListener {

	//
	private ClientFrameManager cfm;

	//
	private JButton btnBrowse;
	private JButton btnAlgo;

	//
	private ClientMain app;

	//
	private JFrame frame;
	private JTextField idField;
	private JButton btnClearId;
	private JTextField nameField;
	private JTextField groupField;
	private JTextField voozField;
	private JTextField etcField;

	//
	private CPTableModel tableModel = new CPTableModel();
	private JTable table;

	/**
	 * 
	 * @param cfm
	 */
	public CodePortionBrowser(ClientFrameManager cfm, ClientMain app) {
		this.cfm = cfm;
		this.app = app;

		frame = cfm.createFrame();
		frame.setContentPane(this);
		frame.setTitle("Browse code portions");
		setLayout(new BorderLayout(0, 0));

		JPanel panel_4 = new JPanel();
		add(panel_4, BorderLayout.CENTER);
		panel_4.setLayout(new BorderLayout(0, 0));

		JSplitPane splitPane = new JSplitPane();
		splitPane.setContinuousLayout(true);
		panel_4.add(splitPane);
		splitPane.setDividerLocation(0.5);

		JPanel panel = new JPanel();
		splitPane.setRightComponent(panel);
		panel.setLayout(new MigLayout("", "[grow]", "[grow][]"));

		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane, "cell 0 0,grow");

		table = new JTable();
		table.setModel(tableModel);
		scrollPane.setViewportView(table);

		JPanel panel_3 = new JPanel();
		panel.add(panel_3, "cell 0 1,grow");
		panel_3.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

		btnBrowse = new JButton("Browse");
		btnBrowse.addActionListener(new BrowseHandler());
		btnBrowse.setHorizontalAlignment(SwingConstants.LEFT);
		panel_3.add(btnBrowse);

		btnAlgo = new JButton("Algorithm");
		btnAlgo.addActionListener(new AlgoHandler());
		panel_3.add(btnAlgo);

		JPanel panel_1 = new JPanel();
		splitPane.setLeftComponent(panel_1);
		panel_1.setLayout(new BorderLayout(0, 0));

		JPanel uploadBtnPanel = new JPanel();
		panel_1.add(uploadBtnPanel, BorderLayout.NORTH);
		uploadBtnPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

		JButton btnUpload = new JButton("Upload");
		btnUpload.addActionListener(new UploadHandler());
		uploadBtnPanel.add(btnUpload);

		JPanel searchPanel = new JPanel();
		searchPanel.setBorder(new TitledBorder(new LineBorder(null), "Search"));

		panel_1.add(searchPanel, BorderLayout.CENTER);
		searchPanel.setLayout(new MigLayout("", "[][grow][]",
				"[][][][][][grow][]"));

		JLabel lblId = new JLabel("id:");
		searchPanel.add(lblId, "cell 0 0,alignx trailing");

		idField = new JTextField();
		searchPanel.add(idField, "cell 1 0,growx");
		idField.setColumns(15);

		btnClearId = new JButton("Clear");
		btnClearId.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				idField.setText("");
			}
		});
		searchPanel.add(btnClearId, "cell 2 0,alignx left,aligny top");

		JLabel lblName = new JLabel("name:");
		searchPanel.add(lblName, "cell 0 1,alignx trailing");

		nameField = new JTextField();
		searchPanel.add(nameField, "cell 1 1,growx");
		nameField.setColumns(15);

		JButton btnClearName = new JButton("Clear");
		btnClearName.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				nameField.setText("");
			}
		});
		searchPanel.add(btnClearName, "cell 2 1");

		JLabel lblGroup = new JLabel("group:");
		searchPanel.add(lblGroup, "cell 0 2,alignx trailing");

		groupField = new JTextField();
		searchPanel.add(groupField, "cell 1 2,growx");
		groupField.setColumns(15);

		JButton btnClearGroup = new JButton("Clear");
		btnClearGroup.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				groupField.setText("");
			}
		});
		searchPanel.add(btnClearGroup, "cell 2 2");

		JLabel lblNewLabel = new JLabel("vooz:");
		searchPanel.add(lblNewLabel, "cell 0 3,alignx trailing");

		voozField = new JTextField();
		searchPanel.add(voozField, "cell 1 3,growx");
		voozField.setColumns(15);

		JButton btnClearVooz = new JButton("Clear");
		btnClearVooz.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				voozField.setText("");
			}
		});
		searchPanel.add(btnClearVooz, "cell 2 3");

		JLabel lblEtc = new JLabel("etc:");
		searchPanel.add(lblEtc, "cell 0 4,alignx trailing");

		etcField = new JTextField();
		searchPanel.add(etcField, "cell 1 4,growx");
		etcField.setColumns(15);

		JButton btnClearEtc = new JButton("Clear");
		btnClearEtc.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				etcField.setText("");
			}
		});
		searchPanel.add(btnClearEtc, "cell 2 4,aligny baseline");

		JPanel panel_2 = new JPanel();
		searchPanel.add(panel_2, "cell 0 6 3 1,grow");
		panel_2.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new SearchHandler());
		panel_2.add(btnSearch);

		JPanel panel_5 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_5.getLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		add(panel_5, BorderLayout.SOUTH);

		//
		table.setColumnSelectionAllowed(false);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		//
		btnBrowse.setEnabled(false);
		btnAlgo.setEnabled(false);
		table.getSelectionModel().addListSelectionListener(
				new TableSelectionHandler());

		JButton btnBack = new JButton("Back");
		btnBack.addActionListener(new BackHandler());
		panel_5.add(btnBack);
		frame.pack();
		frame.setLocationByPlatform(true);
		frame.addWindowListener(new CloseHandler());
		frame.setVisible(true);
	}

	/**
	 * 
	 * @return
	 */
	public Integer getSelectedCPIndex() {
		int i = table.getSelectedRow();
		
		return (Integer) tableModel.getValueAt(i, 0);
	}
	
	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class UploadHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			frame.setVisible(false);
			new CodePortionUploader(cfm, frame, CodePortionBrowser.this);
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class TableSelectionHandler implements ListSelectionListener {

		@Override
		public void valueChanged(ListSelectionEvent arg0) {
			btnBrowse.setEnabled(true);
			btnAlgo.setEnabled(true);
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class BrowseHandler implements ActionListener {

		/**
		 * 
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			frame.setVisible(false);
			new BrowseSource(cfm, frame, getSelectedCPIndex());
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class AlgoHandler implements ActionListener {

		/**
		 * 
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			frame.setVisible(false);
			new AssignedAlgoBrowser(cfm, frame, getSelectedCPIndex());
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class CPTableModel extends AbstractTableModel {

		//
		private Object[][] data = null;

		//
		private String oldName, oldId, oldGroup, oldVooz, oldEtc;

		//
		private String[] columnNames = { "id", "name", "loader", "% done", "time" };

		/**
		 * 
		 * @param id
		 * @param name
		 * @param group
		 * @param vooz
		 * @param etc
		 */
		public void reloadModel(String id, String name, String group,
				String vooz, String etc) {
			this.oldGroup = group;
			this.oldVooz = vooz;
			this.oldName = name;
			this.oldEtc = etc;
			this.oldId = id;

			UsersConsole c = cfm.getConsole();
			try {
				int integerId;
				if (id == null || id.equals("")) {
					integerId = 0;
				} else {
					integerId = Integer.parseInt(id);
				}

				fillData(c.getCodePortionSummaryData(integerId, name, group,
						vooz, etc));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (RemoteException e) {
				e.printStackTrace();
			}

			fireTableStructureChanged();
		}

		/**
		 * 
		 */
		public void reloadModel() {
			reloadModel(oldId, oldName, oldGroup, oldVooz, oldEtc);
		}

		/**
		 * 
		 * @param cpIds
		 */
		private void fillData(List<CPSummaryData> cpDatas) {
			if (cpDatas.size() == 0) {
				data = null;
			} else {
				data = new Object[cpDatas.size()][7];
				int count = 0;

				for (Iterator<CPSummaryData> i = cpDatas.iterator(); i
						.hasNext();) {
					// fill the row
					CPSummaryData cd = i.next();
					// fill id column
					data[count][0] = new Integer(cd.id);
					// fill student name column
					data[count][1] = cd.studName;
					// fill loader name
					data[count][2] = cd.loaderName;
					// fill percent column
					data[count][3] = String.format("%.1f%%", 100 * cd.percent);
					//
					Calendar calendar = Calendar
							.getInstance(Locale.TRADITIONAL_CHINESE);
					calendar.setTimeInMillis(cd.time);

					data[count][4] = String.format("%d.%d.%d; %d:%d",
							calendar.get(Calendar.DAY_OF_MONTH),
							calendar.get(Calendar.MONTH),
							calendar.get(Calendar.YEAR),
							calendar.get(Calendar.HOUR_OF_DAY),
							calendar.get(Calendar.MINUTE)); // TODO

					count++;
				}
			}
		}

		/**
		 * 
		 */
		@Override
		public Class<?> getColumnClass(int columnIndex) {
			if (columnIndex == 0) {
				return Integer.class;
			} else {
				return String.class;
			}
		}

		@Override
		public int getColumnCount() {
			return columnNames.length;
		}

		@Override
		public String getColumnName(int columnIndex) {
			return columnNames[columnIndex];
		}

		@Override
		public int getRowCount() {
			if (data == null) {
				return 0;
			} else {
				return data.length;
			}
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			if (data == null) {
				return null;
			} else {
				return data[rowIndex][columnIndex];
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return false;
		}

		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			throw new IllegalStateException();
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class BackHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			onBack();
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class SearchHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			tableModel.reloadModel(idField.getText(), nameField.getText(),
					groupField.getText(), voozField.getText(),
					etcField.getText());
			btnBrowse.setEnabled(false);
			btnAlgo.setEnabled(false);
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class CloseHandler extends WindowAdapter {

		@Override
		public void windowClosing(WindowEvent e) {
			onBack();
		}
	}

	/**
	 * 
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		tableModel.reloadModel();
	}

	/**
	 * 
	 */
	public void onBack() {
		app.disconnect();
		cfm.disposeFrame(frame);
		app.setVisible(true);
	}
}
